import log4js from 'koa-log4';
import robots from './app/robots';
import { createRedisClient } from './components/redis';
import initMongoose from './components/mongoose';

import {
  REDIS_SKYNET_LOGIN,
  REDIS_SKYNET_LOGOUT,
  REDIS_JANUS_LOGIN,
  REDIS_JANUS_LOGOUT,
} from './app/common/redisChannels';

log4js.configure({
  appenders: [
    { type: 'console' },
    {
      type: 'dateFile',
      filename: 'log/system-topic-consumer.log',
      pattern: '-yyyy-MM-dd',
    },
  ],
});
const logger = log4js.getLogger('SystemTopicConsumer');

initMongoose();
export default function init() {
  const redis = createRedisClient();
  const SYSTEM_EVENTS = [
    'UrgentTeacherReplacement',
    REDIS_JANUS_LOGIN,
    REDIS_JANUS_LOGOUT,
    REDIS_SKYNET_LOGIN,
    REDIS_SKYNET_LOGOUT,
  ];

  SYSTEM_EVENTS.forEach(topic => redis.subscribe(topic));

  const handles = {
    UrgentTeacherReplacement: (topic, payload) => {
      try {
        const parsedPayload = JSON.parse(payload);
        robots.dispatchInternalEvent(topic, parsedPayload);
      } catch (e) {
        logger.error('Receive topic %s with unable parse payload %o', topic, payload);
      }
    },
  };

  redis.on('message', (topic, payload) => {
    const handle = handles[topic];
    if (handle) {
      handle(topic, payload);
    } else {
      logger.debug('Receive topic %s payload %o', topic, payload);
    }
  });

  return redis;
}

init();
logger.info('System Topic Consumer Start Success at %s', new Date().toISOString());

